import React, { useCallback, useMemo, useState } from 'react'
import Test from './Test';
//声明一个数组
// let arr = [12,132,1,241,25,125,12,51,15];

export default function MemoCom() {
  //定义一个状态
  let [count, setCount] = useState(0);
  let [count2, setCount2] = useState(0);
  //声明一个状态
  let [arr, setArr] = useState([12,132,1,241,25,125,12,51,15]);
  //声明一个函数 更新 count 状态   Callback 回调
  let addCount = useCallback(() => {
    //更新
    // setCount(count + 1);
    setCount(a => a + 1);
  }, []);
  //求和
  let total = useMemo(() => {
    console.log('total run.....');
    let sum = 0;
    for(let i=0;i<arr.length;i++){
      sum += arr[i];
    }
    return sum;
  }, [arr]);

  //缓存事件回调
  let addArr = useCallback(() => {
    setArr([...arr, 1]);
  }, []);

  return (
    <div>
      <h2>{count}</h2>
      <button onClick={() => setCount(count + 1)}>新增</button>
      <Test onClick={addCount} />
      <hr />
      <h2>{count2}</h2>
      <button onClick={() => setCount2(count2 + 1)}>新增</button>
      <hr />
      <h2>{total}</h2>
      <button onClick={addArr}>数组中新增一个元素</button>
    </div>
  )
}

